<template>
  <div class="like-container">
    <img src="../assets/icon/dz.svg" alt="点赞图标" width="15" height="15" />
    <span ><span v-if="showButton">点赞数：</span>{{ likeCount }}赞</span>
    <el-button v-if="showButton" type="text" @click="handleLike" >
      {{ isLiked ? '已点赞' : '点赞' }}
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import request from '@/api/request';
import { getToken, parseToken } from "@/api/tokenDecode";

const props = defineProps<{
  targetId: number;
  likeType: number; // 1 表示文章，2 表示评论
  showButton: boolean;
}>();

const showButton = props.showButton ?? true;
const likeCount = ref(0);
const isLiked = ref(false);

// 查询点赞数量
const fetchLikes = async () => {
  try {
    const response = await request.get('/comments/listLikes', {
      params: { targetId: props.targetId, likeType: props.likeType }
    });
    if (!response.data) {
      likeCount.value = 0;
      isLiked.value = false;
      return;
    }
    likeCount.value = response.data.length;
    const token = getToken();
    const userInfo = parseToken(token)?.claims;
    const userId = userInfo?.id;
    isLiked.value = response.data.some((item: any) => item.userId === userId);
  } catch (error) {
    console.error('获取点赞信息失败:', error);
  }
};

// 点赞操作
const handleLike = async () => {

  try {
    const token = getToken();
    const userInfo = parseToken(token)?.claims;
    const userId = userInfo?.id;

    const dto = {
      // 根据 likeType 判断是文章还是评论
      articleId: props.likeType === 1 ? props.targetId : '',
      commentId: props.likeType === 2 ? props.targetId : '',
      // 根据当前点赞状态设置 updateStatus
      updateStatus: isLiked.value ? '1' : '0',
      userId: userId
    };

    // 将对象转换为 URL 查询字符串
    const params = new URLSearchParams(dto).toString();

    await request.post(`/comments/update?${params}`);

    ElMessage.success(isLiked.value ? '取消点赞成功' : '点赞成功');
    isLiked.value = !isLiked.value;
    // 操作成功后重新获取点赞数量
    await fetchLikes();
  } catch (error) {
    ElMessage.error(isLiked.value ? '取消点赞失败' : '点赞失败');
    console.error(isLiked.value ? '取消点赞失败:' : '点赞失败:', error);
  }
};


onMounted(() => {
  fetchLikes();
  console.log('组件已挂载，开始监听点赞事件')
});
</script>

<style scoped>
.like-container {
  display: flex;
  align-items: center;
  gap: 10px;
}
</style>
